<template>
  <el-card style="height: 86vh">
    <el-row justify="space-between">
      <el-col :span="2.5">
        <el-row>
          <el-date-picker
              v-model="searchTimeSelect"
              type="date"
              placeholder="选择生效时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 140px"
          />
          <el-button type="primary"
                     style="margin-left: 10px"
                     @click="handleSearchTimeClick">查 询</el-button>
        </el-row>
      </el-col>
      <el-col :span="2.5">
        <el-button type="primary" @click="handleExportWithTimeClick">导出（时间）</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData"
              border
              v-loading="dataLoading"
              style="width: 100%;margin-bottom: 20px;margin-top: 20px;height: 76vh">
      <el-table-column prop="cityBureau" label="地市局" align="center">
      </el-table-column>
      <el-table-column prop="cumulativeLastYear" label="2024年累计" min-width="100px" align="center">
      </el-table-column>
      <el-table-column prop="cumulativeThisYear" label="2025年累计" min-width="100px" align="center">
      </el-table-column>
      <el-table-column prop="monthlyNew"  label="本月新增" min-width="100px" align="center">
      </el-table-column>
      <el-table-column prop="dailyNew"  label="日新增" min-width="80px" align="center">
      </el-table-column>
      <el-table-column prop="cumulativeOvertime" label="累计超时" min-width="100px" align="center">
      </el-table-column>
      <el-table-column prop="appealRate24h"  label="24小时诉求升级率" min-width="160px" align="center">
      </el-table-column>
      <el-table-column prop="cumulativeAppeal"  label="申诉累计" min-width="100px" align="center">
      </el-table-column>
      <el-table-column prop="cumulativeAppealRate" label="累计申诉率" min-width="120px" align="center">
      </el-table-column>
      <el-table-column prop="dailyAppealNew" label="申诉日新增" min-width="100px" align="center">
      </el-table-column>
      <el-table-column label="累计申诉受理情况说明" min-width="100px" align="center">
        <el-table-column prop="cumulativeAcceptedRejected" label="不受理" min-width="90px" align="center">
        </el-table-column>
        <el-table-column prop="cumulativeAcceptedProcessed" label="已受理" min-width="90px" align="center">
        </el-table-column>
        <el-table-column prop="cumulativeAcceptedPending" label="待处理" min-width="90px" align="center">
        </el-table-column>
      </el-table-column>
      <el-table-column prop="responsibleAppeal"  label="有责申诉" min-width="100px" align="center">
      </el-table-column>
      <el-table-column prop="appealTime"  label="诉求时间" min-width="100px" align="center">
        <template v-slot="scope">
          {{ $filters.dateFilter(scope.row.appealTime)  }}
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <el-dialog v-model="UploadExcelDialogShow" title="上传数据">
    <el-upload
        class="upload-demo"
        method="post"
        multiple=""
        :action="uploadAction"
        :headers="headers"
        style="margin-left: 10px"
        accept=".xlsx,.xls"
        :show-file-list="false"
        :on-progress="handleProgress"
        :on-success="handleSuccess"
        :before-upload="beforeUploadHandle"
        name="files"
    >
      <el-button type="primary">导入</el-button>
    </el-upload>
  </el-dialog>
  <el-dialog v-model="selectTimeDialogShow" title="导出数据" width="300px" @close="beforeclose">
    <!-- <el-row>
      <el-date-picker
          v-model="timeModelValue"
          type="date"
          @change="handleTimePickChange"
          placeholder="选择生效时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 140px;"
      />
    </el-row> -->
    <el-checkbox-group v-model="checkedCities">
    <el-checkbox v-for="item in cities" :key="item.label" :label="item.label" :value="item.value">
      {{ item.label }}
    </el-checkbox>
  </el-checkbox-group>

    <el-row type="flex" justify="center" style="margin-top: 20px">
      <el-button  @click="exportData" type="primary">导出</el-button>
    </el-row>
  </el-dialog>
</template>
<script setup>
import { onMounted, ref,computed } from 'vue'
import utils from '@/utils/utils'
import store from '@/store'
import {
  getDaily12398Data,
  getDataByTime,
  getDaily12398export
} from '@/api/work-order'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { formatYMDDate,getYMD } from '@/utils/timeUtil'
import {addDecimal} from "@/utils/common";

import { exportFile } from "@/utils/export";
const apiBaseUrl=import.meta.env.VITE_API_URL
const uploadAction = computed(() => `${apiBaseUrl}/daily/importDaily95598`);
let headers = {}
const upLoadLoading = ref(false)
const UploadExcelDialogShow = ref(false)
const page = ref(1)
const size = ref(20)
const tableData = ref([])
const dataLoading = ref(false)
const selectTimeDialogShow = ref(false)
const timeModelValue = ref('')
const searchTimeSelect = ref('')
const status=ref('')
const checkedCities = ref([])
const cities = [
  {label:'12398年累计',value:"6"}, 
{label:'12398累计超时',value:"7"}, 
{label:'12398-24小时诉求升级率',value:"8"}, 
]
const handleSearchTimeClick = async () => {
  
  if (searchTimeSelect.value === '') {
    utils.showError('请选择搜索时间...')
    return
  }
  dataLoading.value = true
  const result = await getDataByTime({
    time: searchTimeSelect.value
  })
  tableData.value = result
  dataLoading.value = false
}

const truncateString = (str, maxLength = 10) => {
  if (str.length > maxLength) {
    return str.substring(0, maxLength) + '...';
  }
  return str;
}
const beforeclose=()=>{
  checkedCities.value=[]
}
const getList = async () => {
  dataLoading.value = true
  const result = await getDaily12398Data({
    page: page.value,
    size: size.value
  })
  tableData.value = result
  dataLoading.value = false
}
getList()

const handleProgress = (file) => {
  upLoadLoading.value = true
}

const beforeUploadHandle = (file) => {
  utils.showLoadding('正在上传...')
  return true
}

const handleSuccess = async (res) => {
  if (res.content === 0) {
    utils.showSuccess('上传数据成功')
  }

  UploadExcelDialogShow.value = false
  utils.hideLoadding()
}

const onImportExcelClick = () => {
  UploadExcelDialogShow.value = true
}

const handleExportWithTimeClick = () => {
  selectTimeDialogShow.value = true
}
const exportData= async()=>{
  let exportCount = 0; 
  const statusList = checkedCities.value;
  if (!statusList || statusList.length === 0) {
      ElMessage.warning('请选择需要导出的状态');
      return;
    }
    
  for (const status of statusList) {
      // 构建参数：status 为当前循环的状态值
      const params = {
        time: searchTimeSelect.value,
        status: status // 关键：每次请求只传一个状态值
      }
    let label=  cities.map((item)=>{
      if (item.value===status) {
          return item.label
      }
      })
      try {
          // 调用导出接口
          const res = await getDaily12398export(params);
          // 导出文件（文件名包含状态信息）
          exportFile(res, `12398日报_${label}_${timeModelValue.value}`);
          exportCount++;
          // 延迟500ms，避免浏览器拦截连续下载
          await new Promise(resolve => setTimeout(resolve, 500));
        } catch (error) {
          console.error(`导出失败:  ${label}`, error);
          ElMessage.warning(`[${label}] 导出失败`);
        }
      }
      selectTimeDialogShow.value = false
}
// const exportData = async () => {
//   await axios({
//     method: 'GET',
//     url: `${apiBaseUrl}/complaint/12398/detail/status/export`,
//     responseType: 'blob',
//     params: {
//       time: timeModelValue.value,
//       status:status.value
//     },
//     headers
//   }).then(response => {
//     console.log(response)
//     if (response) {
//       const elink = document.createElement('a')
//       elink.style.display = 'none'
//       const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
//       const blobUrl = URL.createObjectURL(blob)
//       elink.href = blobUrl
//       elink.download = '12398日报-' + formatYMDDate(new Date()) + '.xlsx'
//       document.body.appendChild(elink)
//       elink.click()
//       document.body.removeChild(elink)
//       selectTimeDialogShow.value = false
//     }
//   })
// }

// 表格底部统计方法
const getSummaries = ({ columns, data }) => {
  const sums = []
  const appleValues = data.map(item => Number(item.appealNumerator))
  const orangeValues = data.map(item => Number(item.cumulativeThisYear))
  const appleTotal = appleValues.reduce((prev, curr) => {
    return Number.isNaN(curr) ? prev : prev + curr
  }, 0)
  console.log(appleTotal,"appleTotal");
  const orangeTotal = orangeValues.reduce((prev, curr) => {
    return Number.isNaN(curr) ? prev : prev + curr
  }, 0)
  console.log(`${(appleTotal / orangeTotal * 100).toFixed(2)}` ,"wwwwworangeTotal");
  console.log(`${(appleTotal / orangeTotal * 100).toFixed(2)}`==='NaN' ,"orangeTotal");
  let accept =`${(appleTotal / orangeTotal * 100).toFixed(2)}`==="NaN"? "0.00%" :` ${(appleTotal / orangeTotal * 100).toFixed(2)}% `
  // 计算百分比
  const percentage = orangeTotal !== " "
    ? ` ${accept}` 
    : '0.00%'
    // console.log(percentage);
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计'
      return
    }
    if(column.property === 'cumulativeAppealRate'){
      if (sums[2] === 0) {
        sums[index] =  '0.00%'
      } else {
        sums[index] = (sums[7] * 100 / sums[2]).toFixed(2) + '%'
      }

    } else if(column.property === 'appealRate24h'){
      sums[index] = percentage 
      // console.log(cumulativeThisYear,"2222222");
    } else if(column.property === 'appealTime'){
      sums[index] = tableData.value[0]?.appealTime
    }
     else {
      //页面分别统计 处理
      const values = data.map(item => Number(item[column.property]));
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return addDecimal(prev , curr) ;
          } else {
            return prev;
          }
        }, 0);
      } else {
        sums[index] = ''; //如果列的值有一项不是数字，就显示这个自定义内容
      }
    }
  })
  return sums
}

onMounted(() => {
  searchTimeSelect.value = getYMD(new Date())
  headers = { 'X-Token': store.getters.token }
})
</script>